<?php

function pr($arr, $die=true) {
    echo "<pre>";
    print_r($arr);
    echo "</pre>";
    if ($die) {
        die();
    }
}

function dump($arr, $die=true) {
    echo "<pre>";
    var_dump($arr);
    echo "</pre>";
    if ($die) {
        die();
    }
}date_default_timezone_set("Asia/Kolkata");

function refrenceNoFormat(){
    return 'JK/'.date('dm/Y').'/';
}

function writeToFile($arr) {
    $str = "<pre>";
    $str.=print_r($arr, true);
    $str.="</pre>";

    $fp = fopen('file.txt', 'a');
    fwrite($fp, $str);
    fclose($fp);
}

function printMsg($msg) {
    echo $msg . "\n";
}

function guid() {

    if (function_exists('com_create_guid')) {
        $guid = com_create_guid();
        $guid = preg_replace("/[^A-Za-z0-9]/", "", $guid);
        return $guid;
    } else {
        mt_srand((double) microtime() * 10000); //optional for php 4.2.0 and up.
        $charid = strtoupper(md5(uniqid(rand(), true)));
        $guid = substr($charid, 0, 8)
                . substr($charid, 8, 4)
                . substr($charid, 12, 4)
                . substr($charid, 16, 4)
                . substr($charid, 20, 12);
        return $guid;
    }
}

function createThumb($path, $width, $height, $resize=true) {
    Yii::import("ext.phpthumb.EasyPhpThumb");
    ini_set('upload_max_filesize', '10M');
    ini_set('max_execution_time', '1800');

    $thumbs = new EasyPhpThumb();
    $thumbs->init();

    $thumbs->setThumbsDirectory(aqConfig::getUploadDir());
    if ($resize) {
        $thumbs->load($path)
                ->resize($width, $height);
        return $thumbs->save();
    } else {
        $thumbs->load($path);
        return $thumbs->save();
    }
}

function addhttp($url) {
    if (!preg_match("~^(?:f|ht)tps?://~i", $url)) {
        $url = "http://" . $url;
    }
    return $url;
}

function changePassword($obj, $post) {

    if (isset($post)) {
        $obj->setAttribute('password', md5($post));
        $obj->save(false); // save the change to database
    }
}
function populateEmailTemplate($msgTpl, array $params=NULL) {

    if ($msgTpl != '') {
        $msgTpl = Yii::getPathOfAlias('webroot') . '/protected/views/email/' . $msgTpl;
    }

    $body = '';
    if (file_exists($msgTpl)) {
        $body = file_get_contents($msgTpl);
        foreach ($params as $k => $v)
            $body = str_replace($k, $v, $body);
    }
    return $body;
}

function anotherEmailSend($to, $subject, $body) {
require_once dirname(__FILE__) . '/../protected/extensions/PHPMailer/class.phpmailer.php';
    $mail = new PHPMailer(true);

    $mail->IsSMTP();
    $mail->Host = EMAIL_HOST;
    $mail->SMTPAuth = EMAIL_SMTP_AUTH;
    $mail->Username = EMAIL_USER_NAME;
    $mail->Password = EMAIL_PASSWORD;
    $mail->SetFrom(EMAIL_FROM, '');
    $mail->Subject = $subject;

    try {
        $mail->MsgHTML($body);
        $mail->IsHTML(false); // send as HTML
        $mail->AddAddress($to);
        $mail->Send();
    } catch (Exception $e) {
        
    }
}
function emailSend($name, $userName, $password, $msgTpl=null) {

    require Yii::getPathOfAlias('webroot') . '/protected/extensions/PHPMailer/class.phpmailer.php';

    $mail = new PHPMailer(true);

    $mail->IsSMTP();
    $mail->Host = EMAIL_HOST;
    $mail->SMTPAuth = EMAIL_SMTP_AUTH;
    $mail->Username = EMAIL_USER_NAME;
    $mail->Password = EMAIL_PASSWORD;
    $mail->SetFrom(EMAIL_FROM, 'Why Wait');
    $mail->Subject = 'Your Password successfully created';
    if ($msgTpl && file_exists($msgTpl)) {
        $msgTpl = Yii::getPathOfAlias('webroot') . '/protected/views/email/' . $msgTpl;
    } else {
        $msgTpl = Yii::getPathOfAlias('webroot') . '/protected/views/email/restaurantChangePassword.php';
    }
    $body = '';
    if (file_exists($msgTpl)) {
        $body = file_get_contents($msgTpl);
        $body = str_replace("NAME", $name, $body);
        $body = str_replace("EMAIL", $userName, $body);
        $body = str_replace("PASSWORD", $password, $body);
    }
    try {
        $mail->MsgHTML($body);
        $mail->IsHTML(true); // send as HTML
        $mail->AddAddress($userName);
        $mail->Send();
    } catch (Exception $e) {
        
    }
}

function forgatePasswordEmail($userName, $activationLink, $subject, $msgTpl) {

    require Yii::getPathOfAlias('webroot') . '/protected/extensions/PHPMailer/class.phpmailer.php';

    $mail = new PHPMailer(true);

    $mail->IsSMTP();
    $mail->Host = EMAIL_HOST;
    $mail->SMTPAuth = EMAIL_SMTP_AUTH;
    $mail->Username = EMAIL_USER_NAME;
    $mail->Password = EMAIL_PASSWORD;
    $mail->SetFrom(EMAIL_FROM, 'Why Wait');
    $mail->Subject = $subject;
    $msgTpl = Yii::getPathOfAlias('webroot') . '/protected/views/email/' . $msgTpl;
    // $body = $activationKey;
    $body = '';
    if (file_exists($msgTpl)) {
        $body = file_get_contents($msgTpl);
        $body = str_replace("ACTIVATIONLINK", $activationLink, $body);
    }
    try {
        $mail->MsgHTML($body);
        $mail->IsHTML(true); // send as HTML
        $mail->AddAddress($userName, $name);
        $mail->Send();
    } catch (Exception $e) {
        
    }
}

function dateTime($date, $dateFormate='m-d-Y', $isTime=true, $isAmPm=true, $_12HoursClock=false) {

    $time = "";
    if ($isTime) {
        if ($_12HoursClock) {
            $time = " h:i:s";
        } else {
            $time = " H:i:s";
        }

        if ($isAmPm) {
            $time .= " a";
        }
    }

    $dateFormate = $dateFormate . $time;
    return $date = date($dateFormate, strtotime(str_replace('-', '/', $date)));
}
function dateTimeDeal($date, $dateFormate='m-d-Y') {

  
    return $date = date($dateFormate, strtotime(str_replace('-', '/', $date)));
}
function getReviewRating($id, $is_active=FALSE) {
    $command = Yii::app()->db->createCommand();
    $subSql = '';
    $conditions = array(':id' => $id);

    if ($is_active) {
        $subSql = 'AND is_active=:is_active';
        $conditions = array(':id' => $id, ':is_active' => 1);
    }
    $sql = 'SELECT rating FROM `review` WHERE id=:id ' . $subSql;
    $rating = $command->setText($sql)
            ->queryScalar($conditions);
    return $rating = calculateRating($rating);
}

function getRating($id, $is_active=FALSE) {
    $command = Yii::app()->db->createCommand();

    $subSql = '';
    $conditions = array(':id' => $id);

    if ($is_active) {
        $subSql = 'AND is_active=:is_active';
        $conditions = array(':id' => $id, ':is_active' => 1);
    }

    $rating = $command->setText('SELECT `rating_sum` / `rating_count` AS rating FROM `restaurant` WHERE id=:id ' . $subSql)
            ->queryScalar($conditions);

    return $rating = calculateRating($rating);
}

function calculateRating($rating) {
    if ($rating != null) {
        if ($rating >= MAX_RATING) {
            $rating = 5;
        } elseif ($rating <= MIN_RATING) {
            $rating = 0;
        }
        $constent = (int) $rating;
        $remainder = $rating - $constent;
        if ($remainder != 0) {
            if ($remainder < RATING_MIN_LIMIT) {
                $rem = 0.00;
            } elseif ($remainder >= RATING_MAX_LIMIT) {
                $rem = 1.00;
            } else {

                $rem = 0.5;
            }
            $rating = $constent + $rem;
        }

        return number_format($rating, 2, '.', '');
    }
}

function showRating($rating) {

    $string = '';
    $count = (int) $rating;
    $rem = $rating - $count;
    for ($i = 0; $i < MAX_RATING; $i++) {
        if ($i < $count) {
            $img = 'full.png';
        } elseif ($rem != 0) {
            $img = 'half.png';
            $rem = 0;
        } else {
            $img = 'blank.png';
        }

        $string.='<img src="' . Yii::app()->getBaseUrl() . '/images/' . $img . '">';
    }

    return $string;
}

function getExpireTime() {
//    $increase_time = (int) X_AUTHKEY_INCREASE_EXPIRE_TIME;
//    $calculate_time =(int) 60 * $increase_time;
//    $expires_on = time() + $calculate_time;
    $expires_on = strtotime('1-1-2038');
    return $expires_on;
}

function updateExexpireTime($auth_key) {
    $auth = getAuthKeyObj($auth_key);
    if ($auth) {
        $auth_key = $auth->getAttribute('auth_key');
        $expires_on = getExpireTime();
        $auth->setAttribute('expires_on', $expires_on);
        $auth->update();
    }
}

function getAuthKeyObj($auth_key) {
    $expires_on = time();
    $auth_key_obj = AuthKey::model()->find('auth_key=:auth_key AND expires_on >=:expires_on', array(':auth_key' => $auth_key, ':expires_on' => $expires_on));
    return $auth_key_obj;
}

function getLatLongByAddress($address) {
    $delay = 0;
    $base_url = "http://" . MAPS_HOST . "/maps/geo?output=csv&key=" . KEY;
    $request_url = $base_url . "&q=" . urlencode($address);
    $csv = file_get_contents($request_url) or die("url not loading");
    $csvSplit = explode(",", $csv);
    $status = $csvSplit[0];

    if (strcmp($status, "200") == 0) {
        // successful geocode
        $geocode_pending = false;
        $lat = $csvSplit[2];
        $lng = $csvSplit[3];
    } else if (strcmp($status, "620") == 0) {
        // sent geocodes too fast
        $delay += 100000;
    } else {
        // failure to geocode
        $geocode_pending = false;
        "Address " . $address . " failed to geocoded. ";
        "Received status " . $status . "
        \n";

        usleep($delay);
    }

    return array('lat' => $lat, 'long' => $lng);
}

function clickInfo($id, $checkInto) {
    return $row = Yii::app()->db->createCommand(array(
        'select' => array('*,count(' . $checkInto . ')'),
        'from' => 'trk_restaurant_check_in',
        'where' => 'id=:' . $id,
    ))->queryRow();
}

function checkoutButtonCode() {

    $base = YiiBase::app()->getBasePath();

    require_once($base . '/gc/googlecart.php');
    require_once($base . '/gc/googleitem.php');
    require_once($base . '/gc/googleshipping.php');
    require_once($base . '/gc/googletax.php');

    $merchant_id = "866824847316961";  // Your Merchant ID
    $merchant_key = "Pz3Vs2jfUJeH5F8KiX0QFg";  // Your Merchant Key
    $server_type = "sandbox";
    $currency = "USD";
    $cart = new GoogleCart($merchant_id, $merchant_key, $server_type, $currency);
    $total_count = 1;

    $item_1 = new GoogleItem("Premium Why Wait Membership", // Item name
                    "1 year premium membership of Why Wait", // Item      description
                    $total_count, // Quantity
                    100); // Unit price
    $cart->AddItem($item_1);

    // Add shipping options
    if ($total_count < 3) {
        $ship_1 = new GoogleFlatRateShipping("USPS Priority Mail", 4.55);
    } else {
        $ship_1 = new GoogleFlatRateShipping("USPS Priority Mail", 6.2);
    }
    $Gfilter = new GoogleShippingFilters();
    $Gfilter->SetAllowedCountryArea('CONTINENTAL_48');

    $ship_1->AddShippingRestrictions($Gfilter);

    $cart->AddShipping($ship_1);

    // Add tax rules
    $tax_rule = new GoogleDefaultTaxRule(0.05);
    $tax_rule->SetStateAreas(array("MA"));
    $cart->AddDefaultTaxRules($tax_rule);

    // Specify <edit-cart-url>
    //$cart->SetEditCartUrl("http://localhost/whywait/web/admin/index.php/restaurant/update/54");
    // Specify "Return to xyz" link
    //$cart->SetContinueShoppingUrl("https://www.example.com/goods/");
    // Request buyer's phone number
    //$cart->SetRequestBuyerPhone(true);
    // Display Google Checkout button
    echo $cart->CheckoutButtonCode("SMALL");
}

/* In case the XML API contains multiple open tags
  with the same value, then invoke this function and
  perform a foreach on the resultant array.
  This takes care of cases when there is only one unique tag
  or multiple tags.
  Examples of this are "anonymous-address", "merchant-code-string"
  from the merchant-calculations-callback API
 */

function get_arr_result($child_node) {
    $result = array();
    if (isset($child_node)) {
        if (is_associative_array($child_node)) {
            $result[] = $child_node;
        } else {
            foreach ($child_node as $curr_node) {
                $result[] = $curr_node;
            }
        }
    }
    return $result;
}

/* Returns true if a given variable represents an associative array */

function is_associative_array($var) {
    return is_array($var) && !is_numeric(implode('', array_keys($var)));
}

function googleCheckOutResponce() {
    $base = YiiBase::app()->getBasePath();
    require_once($base . '/gc/googleresponse.php');
    require_once($base . '/gc/googlemerchantcalculations.php');
    require_once($base . '/gc/googleresult.php');
    require_once($base . '/gc/googlerequest.php');

    define('RESPONSE_HANDLER_ERROR_LOG_FILE', 'googleerror.log');
    define('RESPONSE_HANDLER_LOG_FILE', 'googlemessage.log');

    $merchant_id = "778068064150108";  // Your Merchant ID
    $merchant_key = "rFQNe6TbiBeO44y9S9o8Dw";  // Your Merchant Key
    $server_type = "sandbox";  // change this to go live
    $currency = 'USD';  // set to GBP if in the UK

    $Gresponse = new GoogleResponse($merchant_id, $merchant_key);

    $Grequest = new GoogleRequest($merchant_id, $merchant_key, $server_type, $currency);

    //Setup the log file
    $Gresponse->SetLogFiles(RESPONSE_HANDLER_ERROR_LOG_FILE, RESPONSE_HANDLER_LOG_FILE, L_ALL);

    // Retrieve the XML sent in the HTTP POST request to the ResponseHandler
    $xml_response = isset($HTTP_RAW_POST_DATA) ?
            $HTTP_RAW_POST_DATA : file_get_contents("php://input");
    if (get_magic_quotes_gpc()) {
        $xml_response = stripslashes($xml_response);
    }
    list($root, $data) = $Gresponse->GetParsedXML($xml_response);
    $Gresponse->SetMerchantAuthentication($merchant_id, $merchant_key);

    /* $status = $Gresponse->HttpAuthentication();
      if(! $status) {
      die('authentication failed');
      } */

    /* Commands to send the various order processing APIs
     * Send charge order : $Grequest->SendChargeOrder($data[$root]
     *    ['google-order-number']['VALUE'], <amount>);
     * Send process order : $Grequest->SendProcessOrder($data[$root]
     *    ['google-order-number']['VALUE']);
     * Send deliver order: $Grequest->SendDeliverOrder($data[$root]
     *    ['google-order-number']['VALUE'], <carrier>, <tracking-number>,
     *    <send_mail>);
     * Send archive order: $Grequest->SendArchiveOrder($data[$root]
     *    ['google-order-number']['VALUE']);
     *
     */

    switch ($root) {
        case "request-received": {
                break;
            }
        case "error": {
                break;
            }
        case "diagnosis": {
                break;
            }
        case "checkout-redirect": {
                break;
            }
        case "merchant-calculation-callback": {
                // Create the results and send it
                $merchant_calc = new GoogleMerchantCalculations($currency);

                // Loop through the list of address ids from the callback
                $addresses = get_arr_result($data[$root]['calculate']['addresses']['anonymous-address']);
                foreach ($addresses as $curr_address) {
                    $curr_id = $curr_address['id'];
                    $country = $curr_address['country-code']['VALUE'];
                    $city = $curr_address['city']['VALUE'];
                    $region = $curr_address['region']['VALUE'];
                    $postal_code = $curr_address['postal-code']['VALUE'];

                    // Loop through each shipping method if merchant-calculated shipping
                    // support is to be provided
                    if (isset($data[$root]['calculate']['shipping'])) {
                        $shipping = get_arr_result($data[$root]['calculate']['shipping']['method']);
                        foreach ($shipping as $curr_ship) {
                            $name = $curr_ship['name'];
                            //Compute the price for this shipping method and address id
                            $price = 12; // Modify this to get the actual price
                            $shippable = "true"; // Modify this as required
                            $merchant_result = new GoogleResult($curr_id);
                            $merchant_result->SetShippingDetails($name, $price, $shippable);

                            if ($data[$root]['calculate']['tax']['VALUE'] == "true") {
                                //Compute tax for this address id and shipping type
                                $amount = 15; // Modify this to the actual tax value
                                $merchant_result->SetTaxDetails($amount);
                            }

                            if (isset($data[$root]['calculate']['merchant-code-strings']
                                            ['merchant-code-string'])) {
                                $codes = get_arr_result($data[$root]['calculate']['merchant-code-strings']
                                        ['merchant-code-string']);
                                foreach ($codes as $curr_code) {
                                    //Update this data as required to set whether the coupon is valid, the code and the amount
                                    $coupons = new GoogleGiftcerts("true", $curr_code['code'], 10, "debugtest");
                                    $merchant_result->AddGiftCertificates($coupons);
                                }
                            }
                            $merchant_calc->AddResult($merchant_result);
                        }
                    } else {
                        $merchant_result = new GoogleResult($curr_id);
                        if ($data[$root]['calculate']['tax']['VALUE'] == "true") {
                            //Compute tax for this address id and shipping type
                            $amount = 15; // Modify this to the actual tax value
                            $merchant_result->SetTaxDetails($amount);
                        }
                        $codes = get_arr_result($data[$root]['calculate']['merchant-code-strings']
                                ['merchant-code-string']);
                        foreach ($codes as $curr_code) {
                            //Update this data as required to set whether the coupon is valid, the code and the amount
                            $coupons = new GoogleGiftcerts("true", $curr_code['code'], 10, "debugtest");
                            $merchant_result->AddGiftCertificates($coupons);
                        }
                        $merchant_calc->AddResult($merchant_result);
                    }
                }
                $Gresponse->ProcessMerchantCalculations($merchant_calc);
                break;
            }
        case "new-order-notification": {
                $Gresponse->SendAck();
                break;
            }
        case "order-state-change-notification": {
                $Gresponse->SendAck();
                $new_financial_state = $data[$root]['new-financial-order-state']['VALUE'];
                $new_fulfillment_order = $data[$root]['new-fulfillment-order-state']['VALUE'];

                switch ($new_financial_state) {
                    case 'REVIEWING': {
                            break;
                        }
                    case 'CHARGEABLE': {
                            //$Grequest->SendProcessOrder($data[$root]['google-order-number']['VALUE']);
                            //$Grequest->SendChargeOrder($data[$root]['google-order-number']['VALUE'],'');
                            break;
                        }
                    case 'CHARGING': {
                            break;
                        }
                    case 'CHARGED': {
                            break;
                        }
                    case 'PAYMENT_DECLINED': {
                            break;
                        }
                    case 'CANCELLED': {
                            break;
                        }
                    case 'CANCELLED_BY_GOOGLE': {
                            //$Grequest->SendBuyerMessage($data[$root]['google-order-number']['VALUE'],
                            //    "Sorry, your order is cancelled by Google", true);
                            break;
                        }
                    default:
                        break;
                }

                switch ($new_fulfillment_order) {
                    case 'NEW': {
                            break;
                        }
                    case 'PROCESSING': {
                            break;
                        }
                    case 'DELIVERED': {
                            break;
                        }
                    case 'WILL_NOT_DELIVER': {
                            break;
                        }
                    default:
                        break;
                }
                break;
            }
        case "charge-amount-notification": {
                //$Grequest->SendDeliverOrder($data[$root]['google-order-number']['VALUE'],
                //    <carrier>, <tracking-number>, <send-email>);
                //$Grequest->SendArchiveOrder($data[$root]['google-order-number']['VALUE'] );
                $Gresponse->SendAck();
                break;
            }
        case "chargeback-amount-notification": {
                $Gresponse->SendAck();
                break;
            }
        case "refund-amount-notification": {
                $Gresponse->SendAck();
                break;
            }
        case "risk-information-notification": {
                $Gresponse->SendAck();
                break;
            }
        default:
            $Gresponse->SendBadRequestStatus("Invalid or not supported Message");
            break;
    }
}

?>